package namensdienst;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;

import javax.swing.JOptionPane;

public class NameServiceServer extends Thread {
	
	private int nsPort;
	private ServerSocket servSocket;
	private Hashtable<String, NameServiceRemoteObject> listRemoteObjects=null;
	
	public NameServiceServer(int port) throws IOException
	{
		nsPort = port;
		servSocket = new ServerSocket(port);
		if(listRemoteObjects == null)
			listRemoteObjects = new Hashtable<String, NameServiceRemoteObject>();
	}
	
	public void run() {
		System.out.println("NameService server connected. Port: " + nsPort);
		boolean end = false;
		while (!end) {
			try {
				// wait for connections and start thread to handle the
				// connection
				Socket socketReceived = servSocket.accept();
				System.out.println("Connection received");
				NSConnectionTreatment nsct = new NSConnectionTreatment(socketReceived);
				nsct.start();
				//listRemoteObjects = nsct.getListRemoteObjects();
			} catch (IOException e) {
				System.err.println("namesdienst.NameServiceServer: IOException");
				end=true;
			}
		}
	}
	
	public static void main(String[] args) {
        String regExPort = "([0-9]*)";
        
        if (args.length==1 && !args[0].equals("--help") && args[0].matches(regExPort)) {
                NameServiceServer nsServer;
				try {
					nsServer = new NameServiceServer(Integer.parseInt(args[0]));
					//nsServer.setDaemon(true);
	                nsServer.start();
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					System.err.println("The port " + args[0] + " is already used");
				}

        }
        else {
                System.err.println("Usage: java namensdienst.NameServiceServer <name-service-port>");
                System.err.println("Port must contain only the characters '1'...'9'");
        }
		
	}

}
